package main

import (
	"bytes"
	"encoding/binary"
	"fmt"
	"io"
	"io/fs"
	"net"
	"os"
)


func IntToBytes(n int64) []byte {

	bytebuf := bytes.NewBuffer([]byte{})
	binary.Write(bytebuf, binary.BigEndian, n)
	return bytebuf.Bytes()
}

func SendFile(port uint16,fileName string,speed int)  {
	addr := fmt.Sprintf("127.0.0.1:%d",port)
	conn, err := net.Dial("tcp", addr)
	if err != nil{
		panic(err)
	}
	file, err := os.OpenFile(fileName,os.O_RDONLY,fs.ModePerm)
	if err != nil{
		panic(err)
	}
	defer file.Close()

	//send size
	fi, _ := file.Stat()
	fmt.Println(fi.Size())
	//sizeBuf := make([]byte,8)
	sizeBuf := IntToBytes(fi.Size())
	nSend, err := conn.Write(sizeBuf)//TODO send with for
	if err != nil || nSend != len(sizeBuf){
		fmt.Println("send size ",err)
		return
	}


	endFlag := false
	k := 0
	for{
		buf := make([]byte,speed)
		n, err := file.Read(buf)
		if err == io.EOF{
			endFlag = true
		}
		nSend, err := conn.Write(buf[:n])
		if err != nil{
			fmt.Println("sned data err",err)
			break
		}
		fmt.Printf("%d send %d data \n",k,nSend)
		if nSend!= n{
			fmt.Printf("send err")
			break
		}
		//time.Sleep(time.Millisecond*10)
		if endFlag{
			break
		}
		k++
		//if k > 100{
		//	break
		//}
	}
	for  {
		buf := make([]byte,1024)
		n ,_ := conn.Read(buf)
		fmt.Println("respone ", string(buf[:n]))
		break
	}

	conn.Close()
	fmt.Printf("send end")
}
